package table.col;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import table.Col;
import table.Row;
import table.SetDataParamenters;
import table.inter.ISqlCol;
import table.node.BaseNode;
import table.node.DataNode;

public class SqlResultSaveA2BCol  extends SqlResultA2BCol implements ISqlCol{
	private String expression;
	public void setExpression(String expression) {
		this.expression = expression;
	}
	public String getExpression() {
		return expression;
	}
	public DataNode run(HttpServletRequest request){
		String action = request.getParameter("colAction");
		DataNode result = null;
		result = new BaseNode();
		if(action.equals("query")){
			//query relation
			result = this.query(request);
		}
		if(action.equals("add")){
			//add relation
			result.setNodeValue("add");
		}
		if(action.equals("delete")){
			//delete relation
			result.setNodeValue("delete");
			
		}
		if(action.equals("clear")){
			//clear relation
			result.setNodeValue("clear");
		}
		if(action.equals("fresh")){
			result.setNodeValue(this.saveToTable());
		}
		return result;
	}

	public boolean saveToTable(){
		Col aCol = this.getATable().getColByName(this.getName());
		Col idCol = this.getATable().getDataIdCol();
		List<DataNode> oldData = new ArrayList<DataNode>();
		List<DataNode> oldIdData = new ArrayList<DataNode>();
		SetDataParamenters ATParameter = new SetDataParamenters();
		ATParameter.setPageSize(-1);
		ATParameter.addDstColName(aCol.getName());
		ATParameter.addDstColName(idCol.getName());
		try{
			this.getATable().setData(ATParameter);
			oldData.addAll(aCol.getDataList());
			oldIdData.addAll(idCol.getDataList());
			if(oldData.size() != oldIdData.size()){
				return false;
			}
			//->1.Compute all result
			this.setDataByCols(null);
			//->2.Compare the result and saved data,then add to rowList 
			List<DataNode> newData = aCol.getDataList();
			List<DataNode> newIdData = idCol.getDataList();
			if(newData.size() == newIdData.size()){
				List<Row> changeRowList = new ArrayList<Row>();
				for(int i=0; i < oldData.size(); i++){
					try{
						String oldValue = aCol.getColValue(oldData.get(i).getNodeValue()).toString();
						String oldId = idCol.getColValue(oldIdData.get(i).getNodeValue()).toString();
						String newValue = aCol.getColValue(newData.get(i).getNodeValue()).toString();
						String newId = idCol.getColValue(newIdData.get(i).getNodeValue()).toString();
						if(oldId.equals(newId) && !oldValue.equals(newValue)){
							Row row = new Row();
							row.setValueByName(idCol.getName(), newId);
							row.setValueByName(aCol.getName(), newValue);
							changeRowList.add(row);
						}
					}catch(Exception e){}

				}
				//->3.modify ATable which in the rowList
				return this.getATable().modify(changeRowList);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
}
